//
//  YJYVideoView.m
//  BannerViewDemo
//
//  Created by BaizYi on 2019/1/7.
//  Copyright © 2019 BaizYi. All rights reserved.
//

#import "YJYVideoView.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "YJYVideoMaskView.h"

@interface YJYVideoView ()<AVPlayerViewControllerDelegate>

@property(strong,nonatomic) AVPlayerViewController  *videoPlayer;
@property(strong,nonatomic) YJYVideoMaskView  *maskView;

@property(strong,nonatomic) id  timeObserve;



@end

@implementation YJYVideoView

+(instancetype)videoViewFrame:(CGRect)frame videoUrl:(NSString *)videoUrl{
    YJYVideoView *videoView = [[self alloc]initWithFrame:frame];
    videoView.videoUrl = videoUrl;
    return videoView;
}

-(void)setVideoUrl:(NSString *)videoUrl{
    _videoUrl = videoUrl;
    [self configUI];
}

-(void)configUI{
    [self addSubview:self.videoPlayer.view];
    [self addSubview:self.maskView];
    
    __weak typeof(self) weakSelf = self;
    self.maskView.buttonValue = ^(PlayerState state) {
        switch (state) {
            case PlayerStateStart:
                weakSelf.maskView.isStarButton = !weakSelf.maskView.isStarButton;
                weakSelf.isPlay = weakSelf.maskView.isStarButton;
                weakSelf.maskView.isStarButton ? [weakSelf.videoPlayer.player play] :
                [weakSelf.videoPlayer.player pause];
                break;
            case PlayerStateReplay:
                weakSelf.maskView.isStarButton = YES;
                weakSelf.isPlay = weakSelf.maskView.isStarButton;
                
                CMTime dragCMTime = CMTimeMake(0, 1);
                [weakSelf.videoPlayer.player seekToTime:dragCMTime toleranceBefore:CMTimeMake(1, 1) toleranceAfter:CMTimeMake(1, 1) completionHandler:^(BOOL finished) {
                    [weakSelf.videoPlayer.player play];
                }];
                break;
        }
    };
    
    [self.videoPlayer.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        [self createTimer];
    }
}
-(void)createTimer{
    __weak typeof(self) weakSelf = self;
    self.timeObserve = [self.videoPlayer.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, 1) queue:nil usingBlock:^(CMTime time) {
        AVPlayerItem *currentItem = weakSelf.videoPlayer.player.currentItem;
        NSArray *loadedRanges = currentItem.seekableTimeRanges;
        if (loadedRanges.count > 0 && currentItem.duration.timescale != 0) {
            NSInteger currentTime = (NSInteger)CMTimeGetSeconds([currentItem currentTime]);
            CGFloat totalTime = (CGFloat)currentItem.duration.value / currentItem.duration.timescale;
            CGFloat value = CMTimeGetSeconds(currentItem.currentTime) / totalTime;
            [weakSelf.maskView playerCurrentTime:currentTime totalTime:totalTime sliderValue:value];
        }
    }];
}

-(void)start{
    [self.videoPlayer.player play];
}

-(void)stop{
    [self.videoPlayer.player pause];
}



-(AVPlayerViewController *)videoPlayer{
    if (_videoPlayer == nil) {
        _videoPlayer = [[AVPlayerViewController alloc]init];
        _videoPlayer.view.frame = self.frame;
        _videoPlayer.delegate = self;
        _videoPlayer.showsPlaybackControls = NO;
        _videoPlayer.player = [AVPlayer playerWithURL:[NSURL URLWithString:self.videoUrl]];
    }
    return _videoPlayer;
}
-(UIView *)maskView{
    if (_maskView == nil) {
        _maskView = [[YJYVideoMaskView alloc]initWithFrame:self.bounds];
    }
    return _maskView;
}

-(void)dealloc{
    [self stop];
    [self.videoPlayer.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    if (self.timeObserve) {
        [self.videoPlayer.player removeTimeObserver:self.timeObserve];
        self.timeObserve = nil;
    }
}

@end
